import 'package:flutter/material.dart';
import '../api/auth_api.dart';

class LoginScreen extends StatefulWidget {
  const LoginScreen({super.key});

  @override
  _LoginScreenState createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  final _formKey = GlobalKey<FormState>();
  final _identifierController = TextEditingController();
  final _codeController = TextEditingController();
  final _identifierFocus = FocusNode();
  final _codeFocus = FocusNode();
  bool _isLoading = false;
  bool _isCodeSent = false;
  String? _sessionId;

  Future<void> _requestLoginCode() async {
    if (_formKey.currentState!.validate()) {
      setState(() => _isLoading = true);
      try {
        final result = await AuthApi.login(_identifierController.text);
        _sessionId = result;
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('验证码已发送')),
        );
        setState(() => _isCodeSent = true);
      } catch (e) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('登录请求失败: $e')),
        );
      } finally {
        setState(() => _isLoading = false);
      }
    }
  }

  Future<void> _verifyLoginCode() async {
    if (_codeController.text.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('请输入验证码')),
      );
      return;
    }

    setState(() => _isLoading = true);
    try {
      final result =
          await AuthApi.verifyLoginCode(int.parse(_codeController.text));
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('登录成功: ${result.toString()}')),
      );
      // 这里可以保存用户认证信息并重定向到主界面
      Navigator.pop(context);
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('登录验证失败: $e')),
      );
    } finally {
      setState(() => _isLoading = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('用户登录')),
      body: Form(
        key: _formKey,
        child: ListView(
          padding: const EdgeInsets.all(16.0),
          children: [
            TextFormField(
              controller: _identifierController,
              focusNode: _identifierFocus,
              decoration: const InputDecoration(labelText: '用户名或邮箱'),
              validator: (value) => value?.isEmpty == true ? '请输入用户名或邮箱' : null,
            ),
            ElevatedButton(
              onPressed: _isLoading ? null : _requestLoginCode,
              child: _isLoading
                  ? const CircularProgressIndicator()
                  : const Text('获取验证码'),
            ),
            if (_isCodeSent)
              TextFormField(
                controller: _codeController,
                focusNode: _codeFocus,
                keyboardType: TextInputType.number,
                decoration: const InputDecoration(labelText: '验证码'),
              ),
            if (_isCodeSent)
              ElevatedButton(
                onPressed: _isLoading ? null : _verifyLoginCode,
                child: _isLoading
                    ? const CircularProgressIndicator()
                    : const Text('验证并登录'),
              ),
          ],
        ),
      ),
    );
  }
}
